from plugin import plugin

__doc__ = "mailbox"

class mailbox(plugin):
	"Holds messages for you!"
	
	def __init__(self):
		self._version = '3.0 stable'
		self.messagebox = {}
		if self._db:
			rows = self._db._exec("SELECT * FROM mailbox");
			if rows:
				for (to_nick, from_nick, msg) in rows:
					self._add(to_nick, from_nick, msg)

	def _add(self, to_nick, from_nick, msg):
		if to_nick not in self.messagebox:
			self.messagebox[to_nick] = []
		self.messagebox[to_nick].append((from_nick, msg))

	def tell(self, msg, args):
		"Allows you to send messages to people who may not be around at the moment. Messages are sent to them when they next speak. Usage: .tell [name] [message]"
		sender = msg['sender']['name']
		to, _, msg = args.partition(' ')
		if to == '' or msg == '':
			self._irc.reply(msg, self.tell.__doc__)
		self._add(to, sender, msg)
		self._db._exec("INSERT INTO mailbox VALUES(%s, %s, %s);", (to, sender, msg));

	def _onMessage(self, msg):
		sender = msg['sender']['name']
		if sender in self.messagebox:
			for (from_nick, message) in self.messagebox[sender]:
				self._irc.reply(msg, from_nick + ' says: ' + message)
			del self.messagebox[sender]
			self._db._exec("DELETE FROM mailbox WHERE to_nick=%s;", (sender, ));
